package cn.doitedu.javase.calculate_engine.server;

import java.util.HashMap;

public class HttpRequestParser {


    /**
     * 解析http请求的首行，提取其中的url和 参数
     * GET /index.html?user=abc&password=123456 HTTP/1.1
     * @param line
     * @return
     */
    public static UrlAndParams parseHeaderFirst(String line) {

        //

        String[] split = line.split(" ");
        String middle = split[1];

        String[] split1 = middle.split("\\?");
        // /index.html
        String url = split1[0];

        // user=abc&password=123456
        HashMap<String, String> paramMap = new HashMap<>();

        if(split1.length>1) {
            String paramStr = split1[1];

            String[] pairs = paramStr.split("&");
            for (String pair : pairs) {
                String[] kv = pair.split("=");
                paramMap.put(kv[0], kv[1]);
            }
        }

        return new UrlAndParams(url,paramMap);
    }
}
